package me.pearjelly.util;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.pearjelly.model.PageContext;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class PageContextUtil {
	private static final Logger logger = LoggerFactory
			.getLogger(PageContextUtil.class);
	private static final Set<String> md5Set = new HashSet<String>();
	private static final Map<Integer, PageContext> pageCache = Collections
			.synchronizedMap(new LRULinkedHashMap<Integer, PageContext>(20000));
	private static final Pattern PAGEURLREG = Pattern.compile(
			".+((_|-)\\d+)\\.s?html?|$", Pattern.CASE_INSENSITIVE);

	public static String removePageNo(String url) {
		Matcher matcher = PAGEURLREG.matcher(url);
		if (matcher.matches()) {
			return url.substring(0, matcher.start(1))
					+ url.substring(matcher.end(1), url.length());
		} else {
			return url;
		}
	}

	public static String getExtension(PageContext pageContext) {
		String url = getUrl(pageContext);
		return url.substring(url.lastIndexOf(".") + 1);
	}

	public static String getUrl(PageContext pageContext) {
		return pageContext.getWebURL().getURL().toLowerCase();
	}

	public static String getMd5(PageContext pageContext) {
		return DigestUtils.md5Hex(pageContext.getBinaryData());
	}

	public static String getUrlWithoutPageNo(PageContext pageContext,
			String groupPageReg) {
		String url = getUrl(pageContext);
		try {
			if (groupPageReg != null && groupPageReg.trim().length() > 0) {
				Pattern pattern = Pattern.compile(groupPageReg);
				Matcher matcher = pattern.matcher(url);
				if (matcher.matches()) {
					return url.substring(0, matcher.start(1))
							+ url.substring(matcher.end(1));
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return removePageNo(url);
	}

	public static PageContext getParent(PageContext pageContext) {
		return getFromCache(pageContext.getWebURL().getParentDocid());
	}

	public static void putInCache(Integer docId, PageContext pageContext) {
		pageCache.put(docId, pageContext);
	}

	public static PageContext getFromCache(Integer docId) {
		return pageCache.get(docId);
	}

	public static void removeFromCache(Integer docId) {
		pageCache.remove(docId);
	}

	public static boolean existImage(PageContext pageContext) {
		byte[] b = pageContext.getBinaryData();
		if (b != null && b.length > 0) {
			String md5 = PageContextUtil.getMd5(pageContext);
			return md5Set.contains(md5);
		}
		return false;
	}

	public static void rememberMd5(String md5) {
		if (md5 != null && md5.trim().length() > 0) {
			md5Set.add(md5);
		}
	}
}
